using System;
using System.Collections;
using System.Collections.Generic;
using Base;
using UnityEngine;
using UnityEngine.UI;

public class CharactersPanel : MonoBehaviour
{
    [SerializeField] private Button backBtn;
    [SerializeField] Transform itemsParent;
    [SerializeField] GameObject itemPrefab;
    
    private CharacterModel[] allData;
    private void Awake()
    {
        
        TextAsset jsonFile = Resources.Load<TextAsset>("Data/characters");
        CharacterList wrapper = JsonUtility.FromJson<CharacterList>(jsonFile.text);
        allData = wrapper.data;
        Debug.Log(allData.Length);
    }

    void Start()
    {
        backBtn.onClick.AddListener(OnClosePanel);
        EventCenterManager.Instance.AddListener(EventCommand.CharacterSelect,OnCharacterSelect);
        ShowUI();
    }

    private void OnCharacterSelect()
    {
        ShowUI();
    }

    private void ShowUI()
    {
        foreach (Transform child in itemsParent)
        {
            Destroy(child.gameObject);
        }
        int curSelect = GameManager.Instance.playerData.playerID;

        foreach (var itemData in allData)
        {
            CharactersItem item = Instantiate(itemPrefab, itemsParent).GetComponent<CharactersItem>();
            item.id = itemData.id;
            item.nameLabel.text =itemData.name;
            item.charactersIcon.sprite = Resources.Load<Sprite>(itemData.icon);
            item.hpLabel.text = itemData.baseHP.ToString();
            item.speedLabel.text = itemData.baseDamage.ToString();
            if (curSelect == itemData.id)
            {
                item.selectBG.sprite = Resources.Load<Sprite>("Sprites/UI/Generic/ui_button_yellow");
                item.selectLabel.text = "已选择";
            }
            else
            {
                item.selectBG.sprite = Resources.Load<Sprite>("Sprites/UI/Generic/ui_button_green");
                item.selectLabel.text = "未选择";
            }
        }
    }


    private void OnClosePanel()
    { 
        EventCenterManager.Instance.Dispatch(EventCommand.PanelShow,UIPanelShow.LobbyPanel);
        gameObject.SetActive(false);
    }

    private void OnDestroy()
    {
        EventCenterManager.Instance.RemoveListener(EventCommand.CharacterSelect,OnCharacterSelect);

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
